import React, { forwardRef } from "react";
import styled from "@emotion/styled";
import { FiAlertCircle } from "react-icons/fi";
import { duration, easing, radius, spacing } from "../utils/design-tokens";

// Textarea尺寸类型
type TextareaSize = "small" | "medium" | "large";

// Textarea容器
const TextareaContainer = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${spacing["2"]};
  width: 100%;
`;

// Textarea组件样式
const TextareaElement = styled.textarea<{
  $size: TextareaSize;
  $fullWidth?: boolean;
  $hasError?: boolean;
}>`
  width: ${({ $fullWidth }) => ($fullWidth ? "100%" : "auto")};
  border-radius: 6px;
  transition: border-color ${duration.fast}ms ${easing.ease},
    background-color ${duration.fast}ms ${easing.ease};
  font-family: inherit;
  outline: none;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  resize: vertical;
  line-height: 1.5;
  will-change: auto;
  overflow: auto;

  // 尺寸样式
  ${({ $size }) => {
    switch ($size) {
      case "small":
        return `
          padding: ${spacing["2"]} ${spacing["3"]};
          font-size: 0.875rem;
          min-height: 4rem;
          
          @media (max-width: 768px) {
            padding: 0.375rem ${spacing["2"]};
            font-size: 15px;
            min-height: 60px;
          }
        `;
      case "large":
        return `
          padding: ${spacing["3"]} ${spacing["4"]};
          font-size: 1rem;
          min-height: 8rem;
          
          @media (max-width: 768px) {
            padding: ${spacing["2"]} ${spacing["3"]};
            font-size: 16px;
            min-height: 80px;
          }
        `;
      default: // medium
        return `
          padding: ${spacing["2"]} ${spacing["3"]};
          font-size: 0.95rem;
          min-height: 6rem;
          
          @media (max-width: 768px) {
            padding: 0.5rem ${spacing["2"]};
            font-size: 15px;
            min-height: 70px;
          }
        `;
    }
  }}

  // 边框和焦点样式
  ${({ $hasError }) => {
    const borderColor = $hasError
      ? "var(--error-color)"
      : "var(--border-color)";
    const focusBorderColor = $hasError
      ? "var(--error-color)"
      : "var(--accent-color)";

    return `
        border: 1px solid ${borderColor};
        
        &:focus {
          border-color: ${focusBorderColor};
        }
        
        &:hover:not(:focus) {
          border-color: var(--text-secondary);
        }
      `;
  }}

  &::placeholder {
    color: var(--text-tertiary);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    background-color: var(--bg-secondary);
    color: var(--text-tertiary);
  }

  // 自定义滚动条
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: var(--bg-secondary);
    border-radius: ${radius.sm};
  }

  &::-webkit-scrollbar-thumb {
    background: var(--text-tertiary);
    border-radius: ${radius.sm};
  }

  &::-webkit-scrollbar-thumb:hover {
    background: var(--text-secondary);
  }
`;

// 标签样式
const Label = styled.label<{ $required?: boolean; $hasError?: boolean }>`
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  color: ${({ $hasError }) =>
    $hasError ? "var(--error-color)" : "var(--text-primary)"};

  ${({ $required }) =>
    $required &&
    `
    &::after {
      content: ' *';
      color: var(--error-color);
    }
  `}
`;

// 帮助文本
const HelperText = styled.div<{ $hasError?: boolean }>`
  font-size: 0.75rem;
  color: ${({ $hasError }) =>
    $hasError ? "var(--error-color)" : "var(--text-secondary)"};
  display: flex;
  align-items: center;
  gap: ${spacing["1"]};
  line-height: 1.4;
`;

// Textarea组件接口
export interface TextareaProps
  extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  size?: TextareaSize;
  fullWidth?: boolean;
  label?: string;
  helperText?: string;
  errorMessage?: string;
  isRequired?: boolean;
  isInvalid?: boolean;
}

// Textarea组件
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(
  (
    {
      size = "medium",
      fullWidth = true,
      label,
      helperText,
      errorMessage,
      isRequired = false,
      isInvalid = false,
      disabled = false,
      className,
      style,
      ...props
    },
    ref
  ) => {
    const hasError = isInvalid || !!errorMessage;

    // 阻止点击事件冒泡，防止在Modal中误触发关闭
    const handleContainerClick = (e: React.MouseEvent) => {
      e.stopPropagation();
    };

    return (
      <TextareaContainer
        className={className}
        style={style}
        onClick={handleContainerClick}
      >
        {label && (
          <Label $required={isRequired} $hasError={hasError}>
            {label}
          </Label>
        )}

        <TextareaElement
          ref={ref}
          $size={size}
          $fullWidth={fullWidth}
          $hasError={hasError}
          disabled={disabled}
          {...props}
        />

        {(errorMessage || helperText) && (
          <HelperText $hasError={hasError}>
            {hasError && <FiAlertCircle size={12} />}
            {errorMessage || helperText}
          </HelperText>
        )}
      </TextareaContainer>
    );
  }
);

// 设置显示名称
Textarea.displayName = "Textarea";

export default Textarea;
